package com.martin.lib_base.utils

import com.martin.lib_base.ktx.loge
import com.martin.lib_base.net.Api
import com.martin.lib_base.net.interceptor.ProgressInterceptor
import dev.utils.common.FileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * @author：Houge
 * @date：2022/4/10 20:41
 */
object DownloadUtil {

    private const val timeout = 999999999L

    private val api by lazy {
        Retrofit.Builder()
            .client(
                OkHttpClient.Builder()
                    .connectTimeout(timeout, TimeUnit.MILLISECONDS)
                    .readTimeout(timeout, TimeUnit.MILLISECONDS)
                    .callTimeout(timeout, TimeUnit.MILLISECONDS)
                    .addInterceptor(ProgressInterceptor() { url, _, _, progress ->
                        map[url]?.invoke(progress)
                    })
                    .build()
            )
            .baseUrl(Api.BASE_URL)
            .build()
            .create(Api::class.java)
    }

    private val map = HashMap<String, (progress: Int) -> Unit>()

    //下载
    suspend fun download(
        url: String,
        outputFile: String,
        onProgress: (progress: Int) -> Unit = {},
        onSuccess: (file: File) -> Unit = {},
        onError: (message: String) -> Unit = {},
    ) {
        try {
            map[url] = onProgress
            val body = api.download(url)
            val file = File(outputFile)
            withContext(Dispatchers.IO) {
                val saveFile = FileUtils.saveFile(file, body.bytes())
                loge("保存文件成功与否  $saveFile : ${file.path}")
            }
            map.remove(url)
            onSuccess(file)
        } catch (e: Exception) {
            map.remove(url)
            onError(e.message ?: "下载失败:${e::class.java.simpleName}")
        }
    }
}